<template>
	<!-- 面包屑导航区域 -->
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>咨询师信息管理</el-breadcrumb-item>
	</el-breadcrumb>

	<!-- 查询表单区域 -->
	<el-row :gutter="10" class="search-row__inputs" align="middle">
		<el-col :span="6">
			<el-form-item label="咨询师名称">
				<el-input v-model="queryInfo.consultantName" placeholder="请输入咨询师名称" clearable />
			</el-form-item>
		</el-col>
		<el-col :span="6">
			<el-form-item label="咨询师等级">
				<el-select v-model="queryInfo.level" placeholder="请选择咨询师等级" clearable>
					<el-option v-for="level in levelList" :key="level.id" :label="level.levelName" :value="level.id" />
				</el-select>
			</el-form-item>
		</el-col>
		<el-col :span="6">
			<el-form-item label="地址">
				<el-input v-model="queryInfo.consultantAddress" placeholder="请输入地址" clearable />
			</el-form-item>
		</el-col>
		<el-col :span="6">
			<el-form-item label="手机号">
				<el-input v-model="queryInfo.consultantTel" placeholder="请输入手机号" clearable />
			</el-form-item>
		</el-col>
	</el-row>

	<!-- 第二行：操作按钮（搜索、新增、批量删除） -->
	<el-row :gutter="10" class="search-row__actions" align="middle">
		<el-col :span="24">
			<!-- 按钮容器：通过 flex 控制对齐 -->
			<div class="search-actions__btn-group">
				<el-button type="primary" @click="queryDataList">搜索</el-button>
				<el-button type="primary" @click="add"> 新增咨询师</el-button>
				<el-button type="danger" @click="batchRemove"> 批量删除</el-button>
			</div>
		</el-col>
	</el-row>

	<!-- 对话框 新增部分 -->
	<el-dialog :title="title" v-model="dialogFormVisible" width="950" @close="cancle">
		<el-form :model="counselorData" label-width="100">
			<el-form-item label="咨询师名称">
				<el-input v-model="counselorData.consultantName" autocomplete="off" placeholder="请输入咨询师名称"></el-input>
			</el-form-item>
			<el-form-item label="咨询师等级">
				<el-select v-model="counselorData.level" placeholder="请选择咨询师等级" clearable
					@change="val => {counselorData.consultantLevel = levelList.find(l => l.id === val);}">
					<el-option v-for="level in levelList" :key="level.id" :label="level.levelName" :value="level.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="手机号">
				<el-input v-model="counselorData.consultantTel" placeholder="请输入手机号"></el-input>
			</el-form-item>
			<el-form-item label="邮箱">
				<el-input v-model="counselorData.consultantEmail" placeholder="请输入邮箱"></el-input>
			</el-form-item>
			<el-form-item label="地址">
				<el-input v-model="counselorData.consultantAddress" placeholder="请输入地址"></el-input>
			</el-form-item>
			<el-form-item label="头像">
				<el-upload action="http://localhost:8080/upload" list-type="picture-card" :on-success="handleSuccess"
					:limit="1" :on-preview="handlePictureCardPreview" :file-list="fileList" :on-remove="handleRemove"
					:auto-upload="true" class="avatar-uploader">
					<el-icon
						style="width: 128px; height: 128px;border: 1px dashed #DcDFE6; border-radius: 5px;font-size: 1; ">
						<Plus />
					</el-icon>
				</el-upload>
			</el-form-item>
			<el-form-item label="证书图片">
				<el-upload action="http://localhost:8080/upload" list-type="picture-card"
					:on-success="handleCertSuccess" :limit="1" :on-preview="handleCertPreview" :file-list="certFileList"
					:on-remove="handleCertRemove" class="avatar-uploader">
					<el-icon
						style="width: 128px; height: 128px;border: 1px dashed #DcDFE6; border-radius: 5px;font-size: 1; ">
						<Plus />
					</el-icon>
				</el-upload>
			</el-form-item>
			<el-form-item label="咨询师简介">
				<div class="editor-container">
					<QuillEditor theme="snow" v-model:content="counselorData.consultantDes" contentType="html"
						:options="editorOptions" />
					<el-row :gutter="10" class="editor-actions">
						<el-col :span="8" :offset="16">
							<el-button type="primary" @click="show" size="small">
								点击查看HTML内容
							</el-button>
						</el-col>
					</el-row>
				</div>
			</el-form-item>
			<!-- 在表单中添加性别选择 -->
			<el-form-item label="性别">
				<el-radio-group v-model="counselorData.consultantSex">
					<el-radio :label="'男'">男</el-radio>
					<el-radio :label="'女'">女</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="咨询师分类">
				<el-select v-model="counselorData.consultantPos" placeholder="请选择咨询师分类">
					<el-option label="咨询师" :value="1" />
					<el-option label="心理导师" :value="2" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">取 消</el-button>
				<el-button type="primary" @click="confirm">确 定</el-button>
			</div>
		</template>
	</el-dialog>
	<!-- 数据表格 -->
	<el-table :data="dataList" row-key="id" style="width: 100%" @selection-change="handleSelectionChange">
		<el-table-column fixed="left" :data="dataList" type="selection" width="55" />
		<el-table-column fixed="left" property="id" label="ID" width="60" />
		<el-table-column property="consultantName" label="咨询师名称" />
		<el-table-column label="咨询师等级">
			<template #default="scope">{{ scope.row.consultantLevel.levelName || '-' }}</template>
		</el-table-column>
		<el-table-column property="consultantTel" label="手机号" />
		<el-table-column property="consultantEmail" label="邮箱" />
		<el-table-column prop="consultantPic" label="头像">
			<template #default="scope">
				<el-avatar shape="square" size="large"
					:src="'http://localhost:8080'+scope.row.consultantPic"></el-avatar>
			</template>
		</el-table-column>
		<el-table-column prop="consultantCert" label="证书图片">
			<template #default="scope">
				<el-avatar shape="square" size="large"
					:src="'http://localhost:8080'+scope.row.consultantCert"></el-avatar>
			</template>
		</el-table-column>
		<el-table-column property="consultantAddress" label="所属地址" />
		<el-table-column label="简介" min-width="200">
			<template #default="scope">
				<!-- 使用v-html渲染HTML内容，同时限制高度避免表格过高 -->
				<div class="desc-content" v-html="scope.row.consultantDes"></div>
			</template>
		</el-table-column>
		<el-table-column property="consultantPos " label="职位">
			<template #default="scope">
				<el-tag type="primary" v-if="scope.row.consultantPos ==1">咨询师</el-tag>
				<el-tag type="danger" v-else>心理导师</el-tag>
			</template>
		</el-table-column>
		<el-table-column fixed="right" label="操作" min-width="120">
			<template #default="scope">
				<el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
				<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>
	<!-- 书页组件 -->
	<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5,10,15,20]"
		:size="size" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
		@current-change="handleCurrentChange" />
</template>

<script lang="ts" setup>
	import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
	import { ElMessage, ElMessageBox } from 'element-plus'
	import { Plus } from '@element-plus/icons-vue'
	import type { UploadProps, UploadUserFile } from 'element-plus'
	import { QuillEditor } from '@vueup/vue-quill';
	import { computed } from 'vue'
	import '@vueup/vue-quill/dist/vue-quill.snow.css';

	const content = ref('');
	const show = () => {
		console.log(content.value)
	}
	const editorOptions = reactive({
		theme: 'snow',
		modules: {
			toolbar: [
				['bold', 'italic', 'underline', 'strike'],
				['blockquote', 'code-block'],
				[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
				[{ 'list': 'ordered' }, { 'list': 'bullet' }],
				[{ 'indent': '-1' }, { 'indent': '+1' }],
				[{ 'size': ['small', false, 'large', 'huge'] }],
				[{ 'color': [] }, { 'background': [] }],
				[{ 'font': [] }],
				[{ 'align': [] }],
				['link', 'image']
			]
		}
	})
	const dialogImageUrl = ref('') // 图片预览框的地址
	const dialogVisible = ref(false) // 控制图片预览框是否显示
	const fileList = ref([])
	const certFileList = ref([]); // 证书文件列表（类比头像的fileList）
	const certDialogImageUrl = ref(''); // 证书预览地址
	const certDialogVisible = ref(false); // 证书预览框控制

	const handleCertSuccess = (res, file) => {
		console.log("证书上传成功，完整响应:", res);
		if (res && res.data) {
			const filePath = res.data;
			counselorData.value.consultantCert = filePath; // 关键修改：只保存路径字符串
			certFileList.value = [{
				name: file.name,
				url: 'http://localhost:8080' + filePath
			}];
		}
	};

	// 头像上传成功回调（修正）
	const handleSuccess = (res, file) => {
		console.log("头像上传成功，完整响应:", res);
		if (res && res.data) {
			// 直接从响应中提取文件路径字符串
			const filePath = res.data;
			counselorData.value.consultantPic = filePath; // 关键修改：只保存路径字符串
			fileList.value = [{
				name: file.name,
				url: 'http://localhost:8080' + filePath
			}];
		}
	};

	const handleRemove = (file, fileList) => {
		counselorData.value.consultantPic = ''
	}
	const handlePictureCardPreview = (file) => {
		dialogImageUrl.value = file.url;
		dialogVisible.value = true;
	}


	// 证书移除处理（类比头像的handleRemove）
	const handleCertRemove = (file, fileList) => {
		counselorData.value.consultantCert = ''; // 清空证书路径
	};

	// 证书预览处理（类比头像的handlePictureCardPreview）
	const handleCertPreview = (file) => {
		certDialogImageUrl.value = file.url;
		certDialogVisible.value = true;
	};


	const levelList = ref([]);

	const getLevelList = () => {
		axios.get(`/consultantLevel/page`)
			.then(data => {
				if (data) {
					levelList.value = data.list;
					total.value = data.total;
					console.log('等级列表加载成功:', levelList.value);
				} else {
					levelList.value = [];
					total.value = 0;
					console.error('等级列表格式不符合预期:', data);
				}
			})
			.catch(error => {
				levelList.value = [];
				total.value = 0;
				console.error('获取等级列表失败:', error);
			});
	};

	onMounted(() => {
		queryDataList();
		getLevelList();
	});


	const currentPage = ref(1);
	const pageSize = ref(5);
	const size = ref('default');

	const queryInfo = reactive({
		consultantName: '',
		level: '',
		consultantAddress: '',
		consultantTel: '',
		id: '',
		pageNum: 1,
		pageSize: 5
	})

	const total = ref(0);
	const dataList = ref([]);

	const axios = getCurrentInstance().appContext.config.globalProperties.axios;

	const queryDataList = () => {
		axios.get(`/consultant/page`, {
			params: queryInfo,
		}).then((res) => {
			if (!res || !Array.isArray(res.list)) {
				dataList.value = []
				total.value = 0
				ElMessage.error("数据加载失败")
				return
			}
			dataList.value = res.list.map(item => ({
				id: item.id,
				consultantName: item.consultantName,
				consultantTel: item.consultantTel,
				consultantEmail: item.consultantEmail,
				consultantPic: item.consultantPic,
				consultantCert: item.consultantCert,
				consultantAddress: item.consultantAddress,
				consultantDes: item.consultantDes,
				consultantPos: item.consultantPos,
				consultantLevel: item.consultantLevel || {},
				del: item.del ?? 0,
				consultantSex: item.consultantSex,
			}))
			total.value = res.total || 0
		}).catch(error => {
			ElMessage.error("查询失败")
		})
	};

	const multipleSelection = ref([])

	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => {
			return item.id
		})

	}

	const handleSizeChange = (val) => {
		queryInfo.pageSize = val;
		queryDataList();
	}

	const handleCurrentChange = (val) => {
		queryInfo.pageNum = val;
		queryDataList();
	}

	const title = ref('')
	const dialogFormVisible = ref(false)

	const counselorData = ref({
		consultantName: '',
		level: null,
		consultantTel: '',
		consultantEmail: '',
		consultantPic: '',
		consultantSex: "",
		consultantCert: '',
		consultantAddress: "",
		consultantDes: '',
		consultantPos: "",
		consultantLevel: null,
		id: "",
		del: 0
	});


	const cancle = () => {
		counselorData.value = {
			consultantName: '',
			level: '',
			consultantTel: '',
			consultantEmail: '',
			consultantPic: '',
			consultantSex: "",
			consultantCert: '',
			consultantAddress: "",
			consultantDes: '',
			consultantPos: "",
			consultantLevel: null,
			id: "",
			del: 0
		}
		dialogFormVisible.value = false;
		certFileList.value = [];
		certDialogImageUrl.value = '';
		certDialogVisible.value = false;
	}

	const confirm = () => {
		if (counselorData.value.id) {
			console.log("编辑提交的数据:", counselorData.value);
			axios.put(`/consultant/${counselorData.value.id}`, counselorData.value)
				.then((resp) => {
					// 后端返回的字符串在 resp.data 中（无论是否有过滤器）
					const responseStr = resp;
					console.log("后端返回的响应内容:", responseStr); // 调试：查看实际返回的字符串

					if (responseStr.includes('成功')) {
						console.log("提交的数据:", resp);
						ElMessage.success('修改成功');
						queryDataList(); // 刷新表格
						dialogFormVisible.value = false;
					} else {
						ElMessage.error('修改失败：' + responseStr); // 显示后端具体错误
					}
				})
				.catch((error) => {
					ElMessage.error('请求失败：' + error.message);
				});
		} else {
			// 新增逻辑同理，修改判断为 resp.data.includes('成功')
			axios.post('/consultant', counselorData.value)
				.then((resp) => {
					const responseStr = resp;
					if (responseStr.includes('成功')) {
						console.log("提交的数据:", resp);
						ElMessage.success('新增成功');
						// ...其他逻辑
						queryDataList();
						dialogFormVisible.value = false;
					} else {
						ElMessage.error('新增失败：' + responseStr);
					}
				})
				.catch(() => {
					ElMessage.error("新增请求失败");
				});
		}
	};
	const displayLevelName = computed(() => {
		return counselorData.value.consultantLevel?.levelName || '';
	});


	const add = () => {
		title.value = '新增咨询师'
		dialogFormVisible.value = true
	}

	const edit = (row) => {
		title.value = '编辑咨询师';
		dialogFormVisible.value = true;

		// 1. 先深拷贝整行数据（关键！否则其他字段会被初始值覆盖）
		counselorData.value = JSON.parse(JSON.stringify(row));

		// 2. 处理等级回显（基于已拷贝的数据）
		const levelId = counselorData.value.consultantLevel?.id; // 从拷贝后的数据中取等级ID
		if (levelId) {
			counselorData.value.level = levelId; // 赋值给 v-model 绑定的 level（等级ID）
			// 从 levelList 中找到对应的等级对象
			const levelObj = levelList.value.find(l => l.id === levelId);
			counselorData.value.consultantLevel = levelObj || null;
		} else {
			counselorData.value.level = null;
			counselorData.value.consultantLevel = null;
		}

		// 3. 处理头像回显（基于拷贝后的数据）
		const consultantPic = counselorData.value.consultantPic;
		fileList.value = consultantPic
			? [
				{
					name: consultantPic.split('/').pop(),
					url: 'http://localhost:8080' + consultantPic
				}
			]
			: [];

		// 4. 处理证书回显（基于拷贝后的数据）
		const consultantCert = counselorData.value.consultantCert;
		certFileList.value = consultantCert
			? [
				{
					name: consultantCert.substring(consultantCert.lastIndexOf('/') + 1),
					url: 'http://localhost:8080' + consultantCert
				}
			]
			: [];
		
	};

	const remove = (id) => {
		ElMessageBox.confirm('此操作永久删除该文件，是否继续？', '提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			},
		).then(() => {
			axios.delete(`/consultant/${id}`)
				.then(resp => {
					if (resp.includes('成功')) {
						ElMessage.success('删除成功')
						queryDataList()
					} else {
						ElMessage.error('删除失败')
					}
					queryDataList();
				})
		}).catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			})
		})
	}

	const batchRemove = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请选择要删除的项');
			return;
		}

		ElMessageBox.confirm('确定删除选中的咨询师？', '警告', { type: 'warning' })
			.then(() => {
				return axios.delete('/consultant/batch', {
					params: {
						ids: multipleSelection.value
					},
					paramsSerializer: (params) => {
						return new URLSearchParams(params).toString();
					}
				});
			})
			.then(response => {
				if (response.includes('成功')) {
					ElMessage.success('批量删除成功');
					multipleSelection.value = [];
					queryDataList();
				} else {
					ElMessage.error('批量删除失败: ' + response.data);
				}
			})
			.catch(error => {
				if (error !== 'cancel') ElMessage.error("批量删除请求失败");
				else ElMessage.info("已取消删除");
			});
	};
	const getLevelName = (levelId) => {
		const level = levelList.value.find(item => item.id === levelId);
		return level?.levelName || '-';
	};
</script>
<style scoped>
	/* 调整面包屑与搜索框的距离，以及搜索框与按钮的距离 */
	.el-breadcrumb {
		margin-bottom: 0 !important;
		padding: 0 0 10px;
		border-bottom: 1px solid #ddd;
	}

	/* 增加搜索框区域顶部的距离，使其离面包屑更远 */
	.search-row__inputs {
		margin-top: 20px;
		/* 增加这个值可以让搜索框离面包屑更远 */
	}

	/* 减少搜索框与按钮之间的距离 */
	.search-row__actions {
		margin-top: 10px;
		/* 减少这个值可以让按钮离搜索框更近 */
	}

	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon {
		font-size: 28px;
		color: #8c939d;
		text-align: center;
		padding-top: 0;
	}

	.el-pagination {
		margin-top: 15px;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}

	.el-form-item {
		margin-bottom: 16px;
	}

	.search-form {
		min-width: 1200px;
	}

	/* 按钮组样式优化 */
	.search-actions__btn-group {
		display: flex;
		gap: 10px;
		/* 按钮之间的间距 */
	}


	::v-deep .ql-toolbar {
		border: 1px solid var(--el-border-color) !important;
		border-radius: var(--el-border-radius-base) var(--el-border-radius-base) 0 0;
		background-color: var(--el-fill-color-light);
	}

	::v-deep .ql-container {
		min-height: 240px;
		height: auto;
		overflow-y: auto;
		border: 1px solid var(--el-border-color) !important;
		border-top: none !important;
		border-radius: 0 0 var(--el-border-radius-base) var(--el-border-radius-base);
	}

	::v-deep .ql-toolbar button:hover {
		color: var(--el-color-primary) !important;
	}

	::v-deep .ql-container::-webkit-scrollbar {
		width: 6px;
	}

	::v-deep .ql-container::-webkit-scrollbar-thumb {
		background-color: var(--el-border-color);
		border-radius: 3px;
	}

	::v-deep .ql-container::-webkit-scrollbar-thumb:hover {
		background-color: var(--el-color-primary-light-3);
	}

	.editor-container {
		display: flex;
		flex-direction: column;
		width: 100%;
	}

	.editor-actions {
		margin-top: 12px;
		text-align: right;
	}

	.editor-actions .el-button {
		padding: 6px 16px;
		font-size: 14px;
	}

	/* 1. 搜索框行：清除底部间距 */
	.search-row__inputs {
		margin-bottom: 0 !important;
		/* !important 确保覆盖 Element 默认样式 */
	}

	/* 2. 按钮行：清除顶部间距 */
	.search-row__actions {
		margin-top: 0 !important;
		/* !important 确保覆盖 Element 默认样式 */
	}

	/* 3. 按钮组与搜索框对齐（可选，使视觉更紧凑） */
	.search-actions__btn-group {
		display: flex;
		gap: 8px;
		/* 按钮之间的间距，可按需调整 */
		align-items: center;
		/* 与搜索框垂直居中对齐 */
	}
</style>